<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" style="width: 60%;">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      v-loading="formLoading"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="客户名称" prop="customerId">
            <el-select
              filterable
              clearable
              :disabled="formData.customerDefault"
              v-model="formData.customerId"
              @change="handleCustomerChange"
              placeholder="请选择客户"
              class="w-1/1"
            >
              <el-option
                v-for="item in customerList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="店铺编号" prop="storeId">
            <el-select
              :disabled="!formData.customerId"
              v-model="formData.storeId"
              @change="onChangeStore($event)"
              placeholder="请选择店铺"
              class="w-1/1"
            >
              <el-option
                filterable
                clearable
                v-for="item in getStoreOptions"
                :key="item.id"
                :label="item.storeName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
      <el-form-item label="订单名称" prop="orderName">
        <el-input v-model="formData.orderName" placeholder="请输入订单名称" />
      </el-form-item>
        </el-col>
        <el-col :span="12">
      <el-form-item label="订单编号" prop="orderNo">
        <el-input v-model="formData.orderNo" placeholder="请输入订单编号" />
      </el-form-item>
        </el-col>
        <el-col :span="12">
      <el-form-item label="单据编号" prop="slipNo">
        <el-input v-model="formData.slipNo" placeholder="请输入单据编号" />
      </el-form-item>
        </el-col>


        <el-col :span="12">
      <el-form-item label="下单人" prop="ownerUserId">
        <el-select
          v-model="formData.ownerUserId"
          placeholder="请选择负责人"
          class="w-1/1"
        >
          <el-option
            v-for="user in userList"
            :key="user.id"
            :label="user.nickname"
            :value="user.id"
          />
        </el-select>
      </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="订单类型" prop="orderType">
            <el-select
              v-model="formData.orderType"
              placeholder="请选择订单类型"
              clearable
              class="!w-240px"
            >
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.TRADE_ORDER_TYPE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="订单状态" prop="orderStatus">
            <el-select
              v-model="formData.orderStatus"
              placeholder="请选择订单状态"
              clearable
              class="!w-240px"
            >
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.TRADE_ORDER_STATUS)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="交货方式" prop="deliveryType">
            <el-select
              v-model="formData.deliveryType"
              placeholder="请选择交货方式"
              clearable
              class="!w-240px"
            >
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.TRADE_DELIVERY_TYPE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="下单日期" prop="orderDate">
            <el-date-picker
              v-model="formData.orderDate"
              type="date"
              value-format="x"
              placeholder="选择下单日期"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="发货时间" prop="shipTime">
            <el-date-picker
              v-model="formData.shipTime"
              type="date"
              value-format="x"
              placeholder="选择发货时间"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="到货时间" prop="deliveryTime">
            <el-date-picker
              v-model="formData.deliveryTime"
              type="date"
              value-format="x"
              placeholder="选择到货时间"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系人" prop="signContactId">
            <el-select
              filterable
              clearable
              v-model="formData.signContactId"
              :disabled="!formData.customerId"
              @change="onChangeContact($event)"
              class="w-1/1"
            >
              <el-option
                v-for="item in getContactOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系人电话" prop="signContactId">
            <el-input v-model="formData.signContactPhone" placeholder="请输入联系人电话" />
          </el-form-item>
        </el-col>
<!--        <el-col :span="12">-->
<!--          <el-form-item label="公司下单人" prop="signUserId">-->
<!--            <el-input v-model="formData.signUserId" placeholder="请输入公司下单人" />-->
<!--          </el-form-item>-->
<!--        </el-col>-->
        <el-col :span="12">
          <el-form-item label="收货地区编号" prop="areaId">
            <el-cascader
              clearable
              filterable
              v-model="formData.areaId"
              :options="areaList"
              :props="defaultProps"
              class="w-1/1"
              placeholder="请选择收货地区"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="收货详细地址" prop="detailAddress">
            <el-input v-model="formData.detailAddress" placeholder="请输入收货详细地址" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="销售范围" prop="salesScope">
            <el-input v-model="formData.salesScope" placeholder="请输入销售范围" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="销售代理商" prop="salesAgent">
            <el-input v-model="formData.salesAgent" placeholder="请输入销售代理商" />
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 子表的表单 -->
      <ContentWrap>
        <!-- 子表的表单 -->
        <el-tabs v-model="subTabsName">
          <el-tab-pane label="产品清单" name="orderProduct">
            <OrderProductForm ref="orderProductFormRef"  :products="formData.products"
                              :customerId="formData.customerId" :disabled="disabled"/>
          </el-tab-pane>
        </el-tabs>
      </ContentWrap>
      <el-row>
        <el-col :span="12">
          <el-form-item label="产品总金额" prop="totalProductPrice">
            <el-input
              disabled
              v-model="formData.totalProductPrice"
              :formatter="erpPriceInputFormatter"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="整单折扣（%）" prop="discountPercent">
            <el-input-number
              v-model="formData.discountPercent"
              placeholder="请输入整单折扣"
              controls-position="right"
              :min="0"
              :precision="2"
              class="!w-1/1"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="订单总金额" prop="totalPrice">
            <el-input
              disabled
              v-model="formData.totalPrice"
              placeholder="请输入金额"
              :formatter="erpPriceInputFormatter"
            />
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input type="textarea" v-model="formData.remark" placeholder="请输入产品简介" :rows="3" maxlength="120"/>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { DICT_TYPE, getIntDictOptions ,getStrDictOptions} from '@/utils/dict'
import { OrderApi, Order } from '@/api/crm/order'
import * as CustomerApi from "@/api/crm/customer";
import { StoreApi, Store } from '@/api/crm/store'
import * as AreaApi from "@/api/system/area";
import { defaultProps, handleTree } from '@/utils/tree'
import {getSimpleUserList, UserVO} from "@/api/system/user";
import { erpPriceMultiply, erpPriceInputFormatter } from '@/utils'
import {useUserStore} from "@/store/modules/user";
import OrderProductForm from './components/OrderProductForm.vue'
import * as ContactApi from "@/api/crm/contact";

/** CRM 订单 表单 */
// defineOptions({ name: 'OrderForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const userId = useUserStore().getUser.id // 当前登录用户的编号
const formData = ref({
  id: undefined,
  orderName: undefined,
  orderNo: undefined,
  slipNo: undefined,
  customerId: undefined,
  storeId: undefined,
  businessId: undefined,
  contactLastTime: undefined,
  ownerUserId: undefined,
  processInstanceId: undefined,
  auditStatus: undefined,
  orderStatus: undefined,
  orderType: undefined,
  salesScope: undefined,
  salesAgent: undefined,
  orderDate: undefined,
  shipTime: undefined,
  deliveryTime: undefined,
  deliveryType: undefined,
  startTime: undefined,
  endTime: undefined,
  totalProductPrice: undefined,
  discountPercent: 0,
  signContactId: undefined,
  signContactPhone: undefined,
  signUserId: undefined,
  areaId: undefined,
  detailAddress: undefined,
  remark: undefined,
  totalPrice: undefined,
  customerDefault:undefined,
  products: []
})
const formRules = reactive({
  // orderName: [{ required: true, message: '订单名称不能为空', trigger: 'blur' }],
  orderNo: [{ required: true, message: '订单编号不能为空', trigger: 'blur' }],
  slipNo: [{ required: true, message: '单据编号不能为空', trigger: 'blur' }],
  customerId: [{ required: true, message: '客户编号不能为空', trigger: 'blur' }],
  storeId: [{ required: true, message: '店铺不能为空', trigger: 'blur' }],
  // auditStatus: [{ required: true, message: '审批状态不能为空', trigger: 'blur' }],
  orderStatus: [{ required: true, message: '订单状态不能为空', trigger: 'blur' }],
  orderType: [{ required: true, message: '订单类型不能为空', trigger: 'change' }],
  totalProductPrice: [{ required: true, message: '产品总金额不能为空', trigger: 'change' }],
  totalPrice: [{ required: true, message: '订单总金额不能为空', trigger: 'change' }],
})
const formRef = ref() // 表单 Ref
const customerList = ref([]) // 客户列表的数据
const storeList = ref([]) // 客户列表的数据
const areaList = ref([]) // 地区列表
const userList = ref<UserVO[]>([]) // 系统用户
const contactList = ref<ContactApi.ContactVO[]>([]) // 客户联系人列表的数据

/** 子表的表单 */
const subTabsName = ref('orderProduct')
const orderProductFormRef = ref()

/** 计算 discountPrice、totalPrice 价格 */
watch(
  () => formData.value,
  (val) => {
    if (!val) {
      return
    }
    const totalProductPrice = val.products.reduce((prev, curr) => prev + curr.totalPrice, 0)
    const discountPrice =
      val.discountPercent != null
        ? erpPriceMultiply(totalProductPrice, val.discountPercent / 100.0)
        : 0
    const totalPrice = totalProductPrice - discountPrice
    // 赋值
    formData.value.totalProductPrice = totalProductPrice
    formData.value.totalPrice = totalPrice
  },
  { deep: true }
)

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  // 获得客户列表
  customerList.value = await CustomerApi.getCustomerSimpleList()
  storeList.value = await StoreApi.getStoreSimpleList()
  // 获得地区列表
  areaList.value = await AreaApi.getAreaTree()
  // 系统用户列表
  userList.value = await getSimpleUserList()
  // 获取联系人
  contactList.value = await ContactApi.getSimpleContactList()

  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await OrderApi.getOrder(id)
      formData.value.customerDefault = true // 默认客户的选择，不允许变
    } finally {
      formLoading.value = false
    }
  }
  // 默认新建时选中自己
  if (formType.value === 'create') {
    formData.value.ownerUserId = useUserStore().getUser.id
  }

}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 动态获取门店 */
const getStoreOptions = computed(() =>
  storeList.value.filter((item) => item.customerId == formData.value.customerId)
)
/** 动态获取客户联系人 */
const getContactOptions = computed(() =>
  contactList.value.filter((item) => item.customerId == formData.value.customerId)
)
const onChangeStore = (event) => {
  const selectedOptionObj = storeList.value.find(opt => opt.id === event); // 找到对应的对象
  formData.value.areaId = selectedOptionObj.areaId
  formData.value.detailAddress = selectedOptionObj.detailAddress
  // formRef.value?.resetFields()
}
const onChangeContact = (event) => {
  const selectedOptionObj = contactList.value.find(opt => opt.id === event); // 找到对应的对象
  formData.value.signContactPhone = selectedOptionObj.mobile
}
/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 校验子表单
  try {
    await orderProductFormRef.value.validate()
  } catch (e) {
    subTabsName.value = 'orderProduct'
    return
  }
  // 提交请求
  formLoading.value = true
  try {
    // const data =  unref(formData.value) as unknown as Order
    const data = formData.value as unknown as Order
    // 拼接子表的数据
    // data.orderProducts = orderProductFormRef.value.getData()
    // 拼接子表的数据
    if (formType.value === 'create') {
      await OrderApi.createOrder(data)
      message.success(t('common.createSuccess'))
    } else {
      await OrderApi.updateOrder(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    orderName: undefined,
    orderNo: undefined,
    slipNo: undefined,
    customerId: undefined,
    storeId: undefined,
    businessId: undefined,
    contactLastTime: undefined,
    ownerUserId: undefined,
    processInstanceId: undefined,
    auditStatus: undefined,
    orderStatus: undefined,
    orderType: undefined,
    salesScope: undefined,
    salesAgent: undefined,
    orderDate: undefined,
    shipTime: undefined,
    deliveryTime: undefined,
    deliveryType: undefined,
    startTime: undefined,
    endTime: undefined,
    totalProductPrice: undefined,
    discountPercent: undefined,
    signContactId: undefined,
    signUserId: undefined,
    areaId: undefined,
    detailAddress: undefined,
    remark: undefined,
    products: []
  }
  formRef.value?.resetFields()
}

/** 处理切换客户 */
const handleCustomerChange = () => {
  formData.value.businessId = undefined
  formData.value.storeId = undefined
  formData.value.areaId = undefined
  formData.value.detailAddress = undefined
  formData.value.signContactId = undefined
  formData.value.signContactPhone = undefined
  formData.value.products = []
}
</script>
